import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import store from "@/store"
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home',
  },
  {
    path: '/home',
    name: 'home',
    component: HomeView
  },
  {
    path: '/goods',
    name: 'goods',
    component: () => import(/* webpackChunkName: "goods" */ '../views/GoodsView.vue')
  },
  {
    path: '/user',
    name: 'user',
    redirect: "/user/cart",
    component: () => import(/* webpackChunkName: "user" */ '../views/UserView.vue'),
    children:[
      {
        path: 'cart',
        component: () => import(/* webpackChunkName: "usercart" */ '../components/user/Cart.vue')
      },
      {
        path: 'order',
        component: () => import(/* webpackChunkName: "userorder" */ '../components/user/Order.vue')
      },
    ]
  },
  {
    path: '/order',
    name: 'order',
    component: () => import(/* webpackChunkName: "order" */ '../views/OrderView.vue')
  },
  {
    path: '/free',
    name: 'free',
    component: () => import(/* webpackChunkName: "free" */ '../views/FreeView.vue')
  },
  {
    path: '/details',
    name: 'details',
    component: () => import(/* webpackChunkName: "details" */ '../views/DetailsView.vue')
  },
  {
    path:"*",
    component: () => import(/* webpackChunkName: "pagenotfound" */ '../views/PageNotFound.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function(location) {
  return originalPush.call(this, location).catch(err => {})
};


// 路由守卫， 导航守卫  --   全局前置钩子
// router.beforeEach((to,from,next)=>{
//   // 什么时候执行这个函数??  每一次路由跳转之前都执行这个函数
//   // to  要去往的那个路由的对象   to.path 就拿到要去的这个路径
//   // from  从哪里触发的这个路由对象  from.path 就拿到触发的这个路径
//   // console.log("执行了路由守卫");
//   // console.log(from);

//   // 需求：没有登录不能进入个人中心
//   // 实现思路： 先判断是不是去个人中心， 如果是 ，再判断有没有登录， 有登录就放行，没有登录 提示登录
//   if(to.path==="/user"){

//     let token = localStorage.getItem("x-auth-token");
//     if(token){
//       next()
//     }else{

//       // 弹出提示框，请先登录
//       store.dispatch("handleToast/asyncChangeIsShowToast",{
//         msg:"请先登录",
//         type:"warning"
//       })
//       // 回到原来页面
//       router.push(from.path)
//     }
//     return 
    
//   }
//   next() // 放行
// })

export default router
